const Section = tableMap.get("section");
const News = tableMap.get("news");

function formatSection(form) {
	const name = String.asString(form.name).trim();
	if (!name) {
		Throw("ref", "版块名称不可为空")
	}
	const description = String.asString(form.description).trim();

	const createTime = +form.createTime || Date.now();
	return {
		name: name,
		description: description,
		updateTime: Date.now(),
		createTime: createTime,
	}
};

module.exports = {
	prefix: "/section",
	get: {
		"/by_id/:section_id/with_news_list": [{
			des: "获取指定版块以及旗下的新闻",
			emit_with: ["params"]
		}, function*() {

		}],
		"/list_all": [{
			des: "获取所有版块"
		}, function*() {
			this.body = yield Section.find({}).sort([["createTime", -1]]).toArray()
		}]
	},
	post: {
		"/create": [{
			des: "管理员创建版块",
			emit_with: ["session", "form"]
		}, function*() {
			const admin = yield this.admin_loginer();
			const form = this.form;

			yield Section.insertOne(formatSection(form));

			const section = (yield Section.find({}).limit(1).sort([["createTime", -1]]).toArray())[0];

			this.body = section;
		}]
	},
	put: {
		"/update": [{
			des: "管理员修改版块",
			emit_with: ["form", "session"]
		}, function*() {
			const admin = yield this.admin_loginer();
			const form = this.form;

			const _id = form._id;
			if (!_id) {
				Throw("type", "缺少要修改的版块编号");
			}

			const update_form = formatSection(form);
			delete update_form.createTime;

			yield Section.updateOne({
				_id: ["ObjectID", "@", _id]
			}, {
				$set: update_form
			});

			this.body = yield Section.findOne({
				_id: ["ObjectID", "@", _id]
			});
		}]
	},
	delete: {
		"/remove/:section_id": [{
			des: "管理员删除版块",
			emit_with: ["params", "session"]
		}, function*() {
			const admin = yield this.admin_loginer();
			const section_id = this.params.section_id;
			if (!section_id) {
				Throw("type", "缺少要删除的版块编号");
			}

			this.body = yield Section.deleteOne({
				_id: ["ObjectID", "@", section_id]
			});
		}]
	}
};